// 请求数据
let selectData = {};

function init() {
  selectData = JSON.parse(localStorage.getItem("shoppingCart")) || {};
  createSelectDom();
}

init();

ajax("js/shoppingData.json", function (data) {
  createGoodsDom(data);
  addEvent();
});

function createGoodsDom(data) {
  let str = "";
  data.forEach(
    (item) =>
      (str += `
        <tr>
            <td>
                <img src="${item.list[0].img}" />
            </td>
            <td>
                <p>${item.name}</p>
                <div class="color">
                    ${item.list
                      .map((item) => {
                        return `<span data-id="${item.id}">${item.color}</span>`;
                      })
                      .join("")}
                </div>
            </td>
            <td>${item.list[0].price}.00元</td>
            <td>
                <span>-</span>
                <strong>0</strong>
                <span>+</span>
            </td>
            <td><button>加入购物车</button></td>
        </tr>`)
  );

  const tbody = document.querySelector("tbody");
  tbody.innerHTML += str;
}

function addEvent() {
  const trs = document.querySelectorAll(".product tbody tr");
  for (let i = 0; i < trs.length; i++) {
    action(trs[i], i);
  }

  function action(tr, n) {
    const tds = tr.children;
    const img = tds[0].children[0];
    let imgSrc = img.getAttribute("src");
    const name = tds[1].children[0].innerHTML;
    const colors = tds[1].children[1].children;
    const price = parseFloat(tds[2].innerHTML);
    const spans = tds[3].querySelectorAll("span");
    const strong = tds[3].querySelector("strong");
    const joinBtn = tds[4].children[0];
    let selectNum = 0;

    // 颜色按钮点击功能
    let last = null;
    let colorValue = "";
    let colorId = "";
    for (let i = 0; i < colors.length; i++) {
      colors[i].onclick = function () {
        colors[i].index = i;
        last && last !== this && (last.className = "");
        this.className = this.className ? "" : "active";
        colorValue = this.className ? this.innerHTML : "";
        colorId = this.className ? this.dataset.id : "";
        imgSrc = this.className
          ? `images/img_0${n + 1}-${this.index + 1}.png`
          : `images/img_0${n + 1}-1.png`;
        img.src = imgSrc;
        last = this;
      };
    }

    spans[0].onclick = function () {
      selectNum--;
      if (selectNum < 0) {
        selectNum = 0;
      }
      strong.innerHTML = selectNum;
    };

    spans[1].onclick = function () {
      selectNum++;
      strong.innerHTML = selectNum;
    };

    joinBtn.onclick = function () {
      if (!colorValue) {
        return alert("请选择颜色");
      }
      if (!selectNum) {
        return alert("请添加购买数量");
      }

      selectData[colorId] = {
        id: colorId,
        name,
        color: colorValue,
        price,
        num: selectNum,
        img: imgSrc,
        time: new Date().getTime(),
      };

      localStorage.setItem("shoppingCart", JSON.stringify(selectData));

      img.src = `images/img_0${n + 1}-1.png`;
      last.className = "";
      strong.innerHTML = selectNum = 0;

      createSelectDom();
    };
  }
}

function createSelectDom() {
  const tbody = document.querySelector(".selected tbody");
  const totalPrice = document.querySelector(".selected th strong");
  let goods = Object.values(selectData);
  tbody.innerHTML = "";
  tbody.innerHTML = goods
    .sort((v1, v2) => v2.time - v1.time)
    .map(
      (good) =>
        `
        <tr>
            <td>
                <img src="${good.img}" />
            </td>
            <td>
                <p>${good.name}</p>
            </td>
            <td>${good.color}</td>
            <td>${good.price * good.num}.00元</td>
            <td>x${good.num}</td>
            <td><button data-id="${good.id}">删除</button></td>
        </tr>
    `
    )
    .join("");

  totalPrice.innerHTML =
    goods.reduce((pre, cur) => (pre += cur.price * cur.num), 0) + ".00元";

  del();
}

function del() {
  const btns = document.querySelectorAll(".selected tbody button");
  const tbody = document.querySelector(".selected tbody");
  for (let i = 0; i < btns.length; i++) {
    btns[i].onclick = function () {
      delete selectData[this.dataset.id];
      localStorage.setItem("shoppingCart", JSON.stringify(selectData));
      tbody.removeChild(this.parentNode.parentNode);
      const totalPrice = document.querySelector(".selected th strong");
      let goods = Object.values(selectData);
      totalPrice.innerHTML =
        goods.reduce((pre, cur) => (pre += cur.price * cur.num), 0) + ".00元";
    };
  }
}

// storage事件,当前页面不会被监听，会监听其他页面的storage修改
window.addEventListener("storgae", function (e) {
  console.log(e.key); // 修改的是哪一个storage
  console.log(e.newValue); // 修改后的数据
  console.log(e.oldValue); // 修改前的数据
  console.log(e.storageArea); // 修改的storage对象
  console.log(e.url); // 返回操作的url
  init();
});
